package lv.webkursi.web2007a.sem06.upload1;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("serial")
public class FileUpload extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//response.setContentType("text/html; charset=UTF-8");
		
		PrintWriter out = response.getWriter();
		ServletFileUpload upload = new ServletFileUpload();
		upload.setSizeMax(10L * 1024L * 1024L);
		DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(1024,
				new File("/home/ftp"));
		upload.setFileItemFactory(fileItemFactory);

		try {
			List /* FileItem */items = upload.parseRequest(request);
			// Process the uploaded items
			Iterator iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					String name = item.getFieldName();
					String value = item.getString();
					out.println("<p>" + name + ":" + value + "</p>");
				} else {
					String dirName = request.getParameter("dir");
					
					String fieldName = item.getFieldName();
					
					String fileName = item.getName();
					String contentType = item.getContentType();
					boolean isInMemory = item.isInMemory();
					long sizeInBytes = item.getSize();
					
					/* out.println("<table border>");
					
					//out.println("<tr><td>dir:</td><td>" + dirName
					//		+ "</td></tr>");
					
					out.println("<tr><td>fieldName</td><td>" + fieldName
							+ "</td></tr>");
			

					
					out
							.println("<tr><td>fileName</td><td>" + fileName
									+ "</p>");
					out.println("<tr><td>contentType</td><td>" + contentType
							+ "");
					out
							.println("<tr><td>isInMemory</td><td>" + isInMemory
									+ "");
					out.println("<tr><td>sizeInBytes</td><td>" + sizeInBytes
							+ "");
					out.println("</table>"); */
					
					out.println("<h1>File uploaded!</h1>");

					boolean writeToFile = true;
					if (writeToFile) {
						File uploadedFile = new File("/home/ftp/Exercise12_II_UploadPlugin/"+fileName);
						
						item.write(uploadedFile);
						
					} else {
						// InputStream uploadedStream = item.getInputStream();
						// ...
						// uploadedStream.close();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace(out);
		}
	}
}
